package com.demo.netty.session;

import com.demo.netty.model.ChatMessage;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
public class SessionManager {
    private static final Logger logger = LoggerFactory.getLogger(SessionManager.class);
    
    // 存储用户ID与Channel的映射关系
    private final ConcurrentMap<String, Channel> userChannels = new ConcurrentHashMap<>();
    
    // 存储用户ID与离线消息的映射关系
    private final ConcurrentMap<String, ChatMessage> offlineMessages = new ConcurrentHashMap<>();
    
    // 存储所有活跃连接
    private final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
    /**
     * 用户上线，绑定用户与Channel
     */
    public void userOnline(String userId, Channel channel) {
        // 添加空值检查
        if (userId == null || userId.isEmpty()) {
            logger.error("用户ID为空，无法执行用户上线操作");
            return;
        }
        
        if (channel == null) {
            logger.error("Channel为空，无法执行用户上线操作");
            return;
        }
        
        userChannels.put(userId, channel);
        channels.add(channel);
        logger.info("用户 {} 上线", userId);
    }
    
    /**
     * 用户下线
     */
    public void userOffline(String userId) {
        if (userId == null || userId.isEmpty()) {
            logger.error("用户ID为空，无法执行用户下线操作");
            return;
        }
        
        userChannels.remove(userId);
        logger.info("用户 {} 下线", userId);
    }
    
    /**
     * 获取用户Channel
     */
    public Channel getUserChannel(String userId) {
        if (userId == null || userId.isEmpty()) {
            logger.warn("用户ID为空，无法获取用户Channel");
            return null;
        }
        
        return userChannels.get(userId);
    }
    
    /**
     * 保存离线消息
     */
    public void saveOfflineMessage(String userId, ChatMessage message) {
        if (userId == null || userId.isEmpty()) {
            logger.error("用户ID为空，无法保存离线消息");
            return;
        }
        
        if (message == null) {
            logger.error("消息为空，无法保存离线消息");
            return;
        }
        
        offlineMessages.put(userId, message);
        logger.info("为用户 {} 保存离线消息", userId);
    }
    
    /**
     * 获取离线消息
     */
    public ChatMessage getOfflineMessage(String userId) {
        if (userId == null || userId.isEmpty()) {
            logger.warn("用户ID为空，无法获取离线消息");
            return null;
        }
        
        return offlineMessages.remove(userId);
    }
    
    /**
     * 广播消息给所有在线用户
     */
    public void broadcast(Object message) {
        if (message == null) {
            logger.warn("消息为空，无法广播");
            return;
        }
        
        channels.writeAndFlush(message);
    }
    
    /**
     * 获取在线用户数
     */
    public int getOnlineUserCount() {
        return userChannels.size();
    }
}